package com.szholly.pro.watergas_server.common.util;

import com.szholly.data.general.RowBase;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

/**
 * RowBase排序类
 * @author gislin
 * 2016年3月29日
 */
public class RowBaseCompare implements Comparator<RowBase> {
	
	public final static int DESC = 1;
	public final static int ASC = 0;
	private List<ComparatorItem> comparatotItems = new ArrayList<>();
	
	public void addComparatorItem(ComparatorItem item){
		comparatotItems.add(item);
	}
	
	/**
	 * 构造函数
	 * @param fieldName 要排序的字段名
	 * @param sortType 升序或者降序
	 */
	public RowBaseCompare() {

	}

	@Override
	public int compare(RowBase arg0, RowBase arg1) {
		
		for(int i=0;i<comparatotItems.size();i++){
			int sortResult = compareByIndex(i,arg0, arg1);
			if(sortResult != 0){
				return sortResult;
			}
			else{
				continue;
			}
			
		}
		
		return 0;
	}
	
	/**
	 * 比较指定的字段
	 * @param i
	 * @param arg0
	 * @param arg1
	 * @return
	 */
	private int compareByIndex(int i,RowBase arg0, RowBase arg1){
		ComparatorItem item = comparatotItems.get(i);
		String fieldName = item.getFieldName();
		int sortType = item.getSortType();
		String value0 = arg0.getSafeString(fieldName);
		String value1 = arg1.getSafeString(fieldName);
		int sortResult = value0.compareTo(value1);
		if(sortType == DESC){
			sortResult = -sortResult;
		}
		return sortResult;
	}
	
	/**
	 * 针对RowBase的排序项
	 * @author Administrator
	 *
	 */
	public class ComparatorItem{
		private String fieldName;
		private int sortType;
		
		public ComparatorItem(String fieldName,int sortType){
			this.fieldName = fieldName;
			this.sortType = sortType;
		}
		
		public ComparatorItem(String fieldName){
			this.fieldName = fieldName;
			this.sortType = RowBaseCompare.ASC;
		}

		public String getFieldName() {
			return fieldName;
		}

		public void setFieldName(String fieldName) {
			this.fieldName = fieldName;
		}

		public int getSortType() {
			return sortType;
		}

		public void setSortType(int sortType) {
			this.sortType = sortType;
		}
	}
	
}
